package service

import (
	"AiBus/global"
	"AiBus/model"
	"AiBus/request"
	"AiBus/utils"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"io"
	"net/http"
	"time"
)

type WX struct {
	OpenID     string `json:"openid"`
	SessionKey string `json:"session_key"`
}

func Wx_Login(c *gin.Context, req request.WXLogin) {
	//	 https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
	var appid = global.App.Configuration.WX.APPID
	var secret = global.App.Configuration.WX.SECRET
	client := http.Client{}
	// 微信登录请求地址
	resp, err := client.Get("https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + req.Code + "&grant_type=authorization_code")
	if err != nil {
		utils.Fail(c, 400, "微信授权登录失败")
	} else {
		body := resp.Body
		all, err := io.ReadAll(body)
		// 将json格式转换为结构体
		var res WX
		_ = json.Unmarshal(all, &res)
		if err != nil {
			utils.Fail(c, 400, "微信授权登录失败")

		} else {
			userInfo := model.User{}
			tx := global.App.DB.Where("nick_name=?", req.NickName).First(&userInfo)

			if tx.Error != nil {
				now := time.Now().Unix()
				user := model.User{
					OpenId:    res.OpenID,
					NickName:  req.NickName,
					AvatarUrl: req.AvatarUrl,
					Gender:    req.Gender,
				}
				global.App.DB.Create(&user)
				token, err := CreaateToken(res.OpenID)
				if err != nil {
					utils.Fail(c, 400, "用户授权失败")
				} else {
					utils.Success(c, 0, request.WXLoginResp{
						NickName:     user.NickName,
						Token:        token,
						ExpireAt:     now + global.App.Configuration.Server.AccessExpire,
						RefreshAfter: now + global.App.Configuration.Server.AccessExpire/2,
						CreateAt:     user.CreatedAt.Format(time.DateTime),
					})
				}
			} else {
				token, err := CreaateToken(res.OpenID)
				if err != nil {
					utils.Fail(c, 400, "用户授权失败")
				} else {
					now := time.Now().Unix()
					utils.Success(c, 0, request.WXLoginResp{
						NickName:     userInfo.NickName,
						OpenID:       userInfo.OpenId,
						Token:        token,
						ExpireAt:     global.App.Configuration.Server.AccessExpire,
						RefreshAfter: now + global.App.Configuration.Server.AccessExpire/2,
						CreateAt:     userInfo.CreatedAt.Format(time.DateTime)})
				}
			}

		}
	}

}

func CreaateToken(OpenID string) (string, error) {

	token, err := utils.CreateToken(OpenID)
	if err != nil {
		return "", err
	} else {
		return token, nil
	}
}
